package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;

public class CsunewsNewsAnalyse implements AnalyseNews{

	private static final String[] regex={
				"http://www.csunews.com/.*/[0-9]*/[0-9]*/[0-9]*/[0-9]*.html"};
			
			public boolean isDetailPage(String url) {
				for (int i=0; i < regex.length; i++) {
					if (url.matches(regex[i])) {
						return true;
					}
				}
				return false;
			}

			
			public NewsMeta Update(NewsMeta meta) {
				return null;
			}



			
			public NewsMeta parserHtml(UrlMeta urlMeta) {
				NewsMeta news=new NewsMeta();
				String htmltxt=urlMeta.getHtml();
				String url=urlMeta.getUrl();

				String title=null;
				String content=null;
				Long date=null;
				Document doc=Jsoup.parse(htmltxt);
				title=doc.select("h1").text();
				content =HtmlCleaner.getContentHtml(url, doc.select("div.entry-content"));
				if(StringUtils.isBlank(content)){
					content=HtmlCleaner.getContentHtml(url, doc.select("div#content_content_show"));
				}
				if(StringUtils.isBlank(content)){
					content=HtmlCleaner.getContentHtml(url, doc.select(".hk"));
				}
				date=DateUtils.matchDate(doc.select("time").text());
				if(date == null){
					date= DateUtils.matchDate(doc.select("h2").text());
					if(date == null){
						date= DateUtils.matchDate(doc.select(".con_c_x").text());
					}
				}
				if(StringUtils.isBlank(title)){
					title=doc.select("div#cont_left_waik h1").text();
					if(StringUtils.isBlank(title)){
						title=doc.select(".con_c").text();
					}
				}
				String author=null;
				author=JSoupUtils.matchAuthor(doc,"来源:");
				news.setAuthor(author);

				news.setUrl(url);
				news.setTitle(title);
				news.setContent(content);
				news.setDate(date);
				return news;
			}

			public static void main(String[] args) {
				CsunewsNewsAnalyse test=new CsunewsNewsAnalyse();

				String url="http://www.csunews.com/yn/2015/10/10/12225.html";
				UrlMeta meta=CrawlHTML.responseToURL(url);
				NewsMeta parserHtml=test.parserHtml(meta);
				System.out.println(parserHtml);
			}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
